package com.wcity.manage.web.community;

import com.alibaba.fastjson.JSON;
import com.wcity.manage.common.context.Constants;
import com.wcity.manage.common.context.SessionKey;
import com.wcity.manage.common.enums.Code;
import com.wcity.manage.common.enums.SaveImageType;
import com.wcity.manage.common.exception.CustomException;
import com.wcity.manage.common.utils.DwzUtil;
import com.wcity.manage.common.utils.JSONUtil;
import com.wcity.manage.common.utils.RespUtil;
import com.wcity.manage.common.utils.request.RequestUtil;
import com.wcity.manage.common.vo.community.guide.GuideVo;
import com.wcity.manage.common.vo.community.partybuilding.PartyBuildingVo;
import com.wcity.manage.dao.dal.model.PageModel;
import com.wcity.manage.dao.model.Block;
import com.wcity.manage.dao.model.Register;
import com.wcity.manage.dao.model.User;
import com.wcity.manage.dao.model.community.image.ImageUrl;
import com.wcity.manage.dao.model.community.partybuilding.PartyBuilding;
import com.wcity.manage.service.BlockService;
import com.wcity.manage.service.RegisterService;
import com.wcity.manage.service.UserService;
import com.wcity.manage.service.community.image.ImageService;
import com.wcity.manage.service.community.partybuilding.PartyBuildingService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 党政建设
 * Created by hgg on 2016/12/20.
 */
@Controller
public class PartyBuildingAct {

    private final static Logger log = LoggerFactory.getLogger(PartyBuildingAct.class);

    @Autowired
    private PartyBuildingService partyBuildingService;
    @Autowired
    private BlockService blockService;
    @Autowired
    private ImageService imageService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private UserService userService;

    /**
     * 党政建设列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/community_partyBuilding_list")
    public String partyBuildingList( HttpServletRequest request, PageModel model,HttpServletResponse response ) {

        try {

            //【1】封装参数/参数校验
            Map<String, Object> requestMap = RequestUtil.getGetData(request);

            //【2】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询数据
            requestMap.put( "userId", user.getId() );
            requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
            requestMap.put( "end", model.getNumPerPage());
            List<PartyBuildingVo> partyBuildingVos = partyBuildingService.partyBuildingPageList( requestMap );

            //【4】查询总数量
            Integer totalPartyBuilding = partyBuildingService.totalPartyBuilding( requestMap );
            model.setTotal( totalPartyBuilding );

            request.setAttribute( "partyBuildings", partyBuildingVos );
            request.setAttribute( "pageModel", model );
            request.setAttribute( "buildTitle", requestMap.get( "buildTitle" ) );
            request.setAttribute( "blockId", requestMap.get( "blockId" ) );

            //【5】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            List<Block> blocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",blocks );
        } catch ( Exception e ) {
            log.error( "查询党政建设列表异常:" + e.getMessage() );
        }
        return "community/partybuilding/list";
    }

    /**
     * 执行删除党政建设
     *
     * @param request
     */
    @RequestMapping(value = "delete_community_partyBuilding")
    @ResponseBody
    public void deletePartyBuilding( HttpServletRequest request, HttpServletResponse response ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "删除成功";
        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if (requestMap.get("id") == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "请选择一条记录", "", "", "", ""));
                return;
            }

            //【2】执行删除
            Integer deleteNum = partyBuildingService.deletePartyBuilding( requestMap );
            if ( deleteNum == 0 ) {
                code = Constants.STATUS_ERROR_DWZ;
                message = "删除失败";
            }
        } catch ( Exception e ) {
            log.error( "删除党政建设异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "删除失败";
        }
        RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(code, message, "", "", "", ""));
    }

    /**
     * 新增党政建设
     *
     * @param partyBuilding
     * @param response
     */
    @RequestMapping(value = "save_add_community_partyBuilding")
    @ResponseBody
    public void addPartyBuilding( PartyBuilding partyBuilding, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "保存成功";

        try {
            //【1】校验参数
            String imgUrl = request.getParameter( "imageUrl" );
            String blockIdStr = request.getParameter( "blockIdStr" );
            if ( StringUtils.isBlank( partyBuilding.getBuildTitle() ) || StringUtils.isBlank( imgUrl )
                    || StringUtils.isBlank( partyBuilding.getBuildContent() ) || StringUtils.isBlank( blockIdStr ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行保存党政建设
            partyBuilding.setUserId( user.getId() );
            partyBuildingService.saveAddPartyBuilding( partyBuilding,imgUrl,blockIdStr );

        } catch ( Exception e ) {
            log.error( "保存党政建设异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "保存失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_partyBuilding_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到编辑党政建设页面
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "to_edit_community_partyBuilding")
    public String partyBuildingDetail( HttpServletRequest request, HttpServletResponse response ) {

        try {

            //【1】校验参数
            Map<String, Object> requestMap = RequestUtil.getGetData( request );
            if ( requestMap.get("id") == null ) {
                return null;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if ( user == null ) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【3】查询党政建设数据
            requestMap.put("userId", user.getId());
            PartyBuildingVo partyBuildingVo = partyBuildingService.partyBuildingDetail( requestMap );
            request.setAttribute( "partyBuilding", partyBuildingVo );
            if (partyBuildingVo == null) {
                RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "数据不存在", "", "", "", ""));
                return null;
            }

            //【4】查询用户管理的未选择的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            queryMap.put( "id",requestMap.get("id") );
            String blocks = partyBuildingService.blockIds( queryMap );
            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryNotBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blockNots",queryNotBlocks );

            //【4】查询用户管理的已选择的小区列表
            queryMap.put( "id",requestMap.get("id") );
            blocks = partyBuildingService.blockIds( queryMap );
            queryMap.put( "id",null );
            queryMap.put( "notContain",null );
            queryMap.put( "contain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

            //【5】查询封面
            Map<String,Object> queryImageMap = new HashedMap();
            queryImageMap.put( "referId",requestMap.get( "id" ) );
            queryImageMap.put( "saveType", SaveImageType.COMMUNITY_PARTY_BUILDING );
            List<ImageUrl> imageUrls = imageService.images( queryImageMap );
            if( CollectionUtils.isNotEmpty( imageUrls ) ){
                request.setAttribute( "image",imageUrls.get(0) );
            }

        } catch ( Exception e ) {
            log.error( "查询党政建设失败: " + e.getMessage() );
            RespUtil.sendJson(response, DwzUtil.getRetAjaxJson(Constants.STATUS_ERROR_DWZ, "查询失败", "", "", "", ""));
        }

        return "community/partybuilding/edit";
    }

    /**
     * 更新党政建设
     *
     * @param partyBuilding
     * @param response
     */
    @RequestMapping(value = "save_edit_community_partyBuilding")
    @ResponseBody
    public void updatePartyBuilding( PartyBuilding partyBuilding, HttpServletResponse response, HttpServletRequest request ) {

        String code = Constants.STATUS_SUCCESS_DWZ;
        String message = "更新成功";

        try {

            //【1】校验参数
            String imageUrl = request.getParameter( "imageUrl" );
            String blockIdStr = request.getParameter( "blockIdStr" );
            if ( StringUtils.isBlank( partyBuilding.getBuildContent() ) || StringUtils.isBlank( imageUrl ) || StringUtils.isBlank( partyBuilding.getBuildTitle() ) ) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "参数错误", "", "", "", "" ) );
                return;
            }
            //【2】获取用户
            User user = (User) request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if (user == null) {
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return;
            }

            //【3】执行更新党政建设
            partyBuilding.setUserId( user.getId() );
            partyBuildingService.saveUpdatePartyBuilding( partyBuilding,imageUrl,blockIdStr );

        } catch ( Exception e ) {
            log.error( "更新党政建设异常：" + e.getMessage() );
            code = Constants.STATUS_ERROR_DWZ;
            message = "更新失败";
        }
        RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( code, message, "community_partyBuilding_list", "", "closeCurrent", "" ) );
    }

    /**
     * 跳转到添加党政建设的页面
     * @return
     */
    @RequestMapping(value = "to_add_community_partyBuilding")
    public String toAddPartyBuilding( HttpServletRequest request,HttpServletResponse response ){

        try {

            //【1】获取当前用户信息
            User user = (User)request.getSession().getAttribute( SessionKey.SESSION_USER_INFO );
            if( user == null ){
                RespUtil.sendJson( response, DwzUtil.getRetAjaxJson( Constants.STATUS_ERROR_DWZ, "登录超时", "", "", "", "" ) );
                return null;
            }

            //【2】查询用户管理的小区列表
            Map<String,Object> queryMap = new HashMap<>();
            queryMap.put( "userId",user.getId() );
            String blocks = partyBuildingService.blockIds( queryMap );
//            queryMap.put( "notContain",1 );
            queryMap.put( "ids",blocks );
            List<Block> queryBlocks = blockService.getAdminHaveBlockList( queryMap );
            request.setAttribute( "blocks",queryBlocks );

        }catch ( Exception e ){
            log.error( "跳转到办事指南页面异常：" + e.getMessage() );
        }
        return "community/partybuilding/add";
    }
/*****************************************H5***********************************************/
    /**
     * 党政建设列表(H5)
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "community_partyBuilding_list_h5")
    @ResponseBody
    public Object partyBuildingListH5( HttpServletRequest request, PageModel model,HttpServletResponse response ) {


        //【1】校验参数
        Map<String,Object> requestMap = new HashedMap();
        String surveyId = request.getParameter( "surveyId" );
        if( StringUtils.isBlank( surveyId ) ){
            throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
        }
//
//        //【2】获取当前用户信息
//        Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
//        if( userMap == null || userMap.get( "blockId" ) == null ){
//            throw new CustomException( "用户信息不存在", Code.ERROR );
//        }

        Block block = blockService.getBlockById( Integer.parseInt( surveyId ) );
        if( block == null ){
            throw new CustomException( "小区不存在", Code.ERROR );
        }
        //【3】查询数据
        requestMap.put( "userId",block.getUserId() );
        requestMap.put( "blockId",block.getId() );
        requestMap.put( "start", ( model.getPageNum() - 1) * model.getNumPerPage() );
        requestMap.put( "end", model.getNumPerPage() );
        List<PartyBuildingVo> partyBuildingVos = partyBuildingService.partyBuildingPageList( requestMap );

        //【4】查询总数量
        Integer totalPartyBuilding = partyBuildingService.totalPartyBuilding( requestMap );
        model.setTotal( totalPartyBuilding );

        Map<String,Object> map = JSONUtil.getSuccessJson();
        map.put( "partyBuildings",partyBuildingVos );
        map.put( "pageModel",model );

        return map;
    }

    /**
     * 党政建设详情
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "edit_community_partyBuilding_h5")
    @ResponseBody
    public Object partyBuildingDetailH5( HttpServletRequest request, HttpServletResponse response ) {

        //【1】校验参数
        Map<String,Object> requestMap = new HashedMap();
        String surveyId = request.getParameter( "surveyId" );
        String id = request.getParameter( "id" );
        if( StringUtils.isBlank( surveyId ) || StringUtils.isBlank( id ) ){
            throw new CustomException( Constants.PARAMETER_ERROR, Code.ERROR );
        }

        //【2】获取当前用户信息
//        Map<String,Object> userMap = (Map<String,Object>)registerService.registerInfo( registerId );
//        if( userMap == null || userMap.get( "blockId" ) == null ){
//            throw new CustomException( "用户信息不存在", Code.ERROR );
//        }

        Block block = blockService.getBlockById( Integer.parseInt( surveyId ) );
        if( block == null ){
            throw new CustomException( "小区不存在", Code.ERROR );
        }
        //【3】查询党政建设数据
        requestMap.put( "id", Integer.parseInt( id ) );
        requestMap.put( "userId",block.getUserId() );
        PartyBuildingVo partyBuildingVo = partyBuildingService.partyBuildingDetail( requestMap );
        if ( partyBuildingVo == null ) {
            throw new CustomException( "数据不存在", Code.ERROR );
        }

        Map<String,Object> map = JSONUtil.getSuccessJson();
        map.put( "data",partyBuildingVo );

        //【4】查询封面
        Map<String,Object> queryImageMap = new HashedMap();
        queryImageMap.put( "referId",requestMap.get( "id" ) );
        queryImageMap.put( "saveType", SaveImageType.COMMUNITY_PARTY_BUILDING );
        List<ImageUrl> imageUrls = imageService.images( queryImageMap );
        if( CollectionUtils.isNotEmpty( imageUrls ) ){
            request.setAttribute( "image",imageUrls.get(0) );
            map.put( "image",imageUrls.get(0) );
        }
        return map;
    }
}
